package util;

import java.util.Enumeration;
import java.util.Hashtable;


public class Preferences {
	Hashtable prefsHashtable;
	Storage myStorage;
	char recordDelimiter = 13;
	char fieldDelimiter = 9;
	public Preferences(String _name){
		myStorage = new Storage(_name);

		loadPrefs();
	}
	public Hashtable loadPrefs(){
		prefsHashtable = new Hashtable();
		String prefsText = myStorage.getText();
		//System.out.println("Loading Prefs" + prefsText);
		String[] pairs = Storage.split(prefsText,recordDelimiter);
		for(int i = 0; i < pairs.length; i++){
			String[] pair = Storage.split(pairs[i],fieldDelimiter);
			if (pair.length > 1){
				//System.out.println(pair[0] + " " + pair[1]);
				prefsHashtable.put(pair[0],pair[1]);
			}
		}
	
		return prefsHashtable;
	}
	public void savePrefs(){
	
		String allPrefs = "";
		Enumeration e = prefsHashtable.keys();
		boolean firstTime = true;
		while(e.hasMoreElements()){
			String key = (String) e.nextElement();
			String value = (String) prefsHashtable.get(key);
			if (!firstTime)	allPrefs = allPrefs + recordDelimiter ;
			firstTime = false;
			allPrefs = allPrefs + key + fieldDelimiter + value;

		}

//System.out.println("Setting Prefs" + allPrefs);
		myStorage.setText(allPrefs);
	}
	
	public void setPref(String _key, String _value){
	//	System.out.println("key" + _key + " value" + _value);	
		prefsHashtable.put(_key,_value);
			
	}
	public void setPref(String _key, boolean _value){
		//	System.out.println("key" + _key + " value" + _value);	
			prefsHashtable.put(_key,String.valueOf(_value));
				
		}
	public void setPref(String _key, int _value){
		//	System.out.println("key" + _key + " value" + _value);	
			prefsHashtable.put(_key,String.valueOf(_value));
				
		}
	public void setPref(String _key, long _value){
		//	System.out.println("key" + _key + " value" + _value);	
			prefsHashtable.put(_key,String.valueOf(_value));
				
		}
	public void done(){
		savePrefs();
		myStorage.done();
	}
	
	public String getPref(String _key){
		if (prefsHashtable.containsKey(_key)){
			return(String) prefsHashtable.get(_key);
		}else{
			return null;
		}
	}
	
	
}
